// main.go
package main

import (
	"bufio"
	"bytes"
	"path/filepath"

	"flag"
	"fmt"
	"os"
	"regexp"
	"strconv"
)

func main() {
	flag.Parse()
	name := flag.Arg(0)
	delt, err := strconv.ParseFloat(flag.Arg(1), 64)
	if err != nil {
		panic(err)
	}
	fmt.Printf("File:%v\nShift:%v\n", name, delt)
	fp, err := os.Open(name)
	if err != nil {
		panic(err)
	}
	defer fp.Close()
	dir1 := filepath.Dir(name)
	name1 := filepath.Base(name)
	out, err := os.Create(filepath.Join(dir1, "shift-"+name1))
	if err != nil {
		panic(err)
	}
	defer out.Close()

	r := bufio.NewReader(fp)
	reg1 := regexp.MustCompile(`^\d+:\d{1,2}:\d{1,2},\d{1,3}\s* --> \s*\d+:\d{1,2}:\d{1,2},\d{1,3}`)
	var idx = 1
	for {
		s, err := r.ReadSlice('\n')
		if err != nil {
			break
		}
		if reg1.Match(s) {
			fmt.Println(idx)
			idx++
			fmt.Println(string(bytes.TrimSpace(s)))
			s1, _ := shift_time(s, delt)
			fmt.Printf("%s\r\n", string(s1))
			out.Write(s1)
		} else {
			//fmt.Println(string(s))
			out.Write(s)
		}
	}
}

func shift_time(s []byte, d float64) ([]byte, error) {
	reg2 := regexp.MustCompile(`(\d+):(\d{1,2}):(\d{1,2}),(\d{1,3})`)
	vs := bytes.Split(s, []byte(" --> "))
	if len(vs) != 2 {
		return s, fmt.Errorf("time format error")
	}
	for i := 0; i < 2; i++ {
		vs[i] = bytes.TrimSpace(vs[i])
	}
	secs1 := reg2.FindAllSubmatch(vs[0], 1)
	secs2 := reg2.FindAllSubmatch(vs[1], 1)
	//fmt.Println(secs1[0])
	//全部转为秒，浮点数
	tv1 := byteArrayToSeconds(secs1[0][1:])
	tv1 += d
	tStr1 := SecondsToString(tv1)

	tv2 := byteArrayToSeconds(secs2[0][1:])
	tv2 += d
	tStr2 := SecondsToString(tv2)
	return []byte(fmt.Sprintf("%v --> %v\r\n", tStr1, tStr2)), nil
}

func byteArrayToSeconds(secs [][]byte) float64 {
	v1, _ := strconv.Atoi(string(secs[0]))
	tv1 := float64(v1 * 3600)
	v1, _ = strconv.Atoi(string(secs[1]))
	tv1 += float64(v1 * 60)
	v1, _ = strconv.Atoi(string(secs[2]))
	tv1 += float64(v1)
	v1, _ = strconv.Atoi(string(secs[3]))
	tv1 += float64(v1) / 1000
	return tv1
}

func SecondsToString(seconds float64) string {
	sec_int := int(seconds)
	ms := int(seconds*1000) - sec_int*1000
	s := sec_int % 60
	mAll := (sec_int - s) / 60
	m := mAll % 60
	h := (mAll - m) / 60
	return fmt.Sprintf("%02d:%02d:%02d,%03d", h, m, s, ms)
}
